package com.fz.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.fz.controller.request.BaseRequest;
import com.fz.controller.request.UserPageRequest;
import com.fz.mapper.UserMapper;
import com.fz.pojo.User;
import com.fz.service.UserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> list() {
        return userMapper.list();
    }

    //分页
    @Override
    public PageInfo<User> page(BaseRequest baseRequest) {
        PageHelper.startPage(baseRequest.getPageNum(), baseRequest.getPageSize());
        List<User> users = userMapper.listByCondition(baseRequest);
        return new PageInfo<>(users);
    }

    //添加用户
    @Override
    public void addUser(User user) {
        //日期
        Date date = new Date();

        //当作卡号来处理 前面日期+ 后面uuid hashCode返回纯数字,拼接在日期后面 当作卡号
        //由于返回可能有负数 所以取绝对值
        user.setUsername(DateUtil.format(date, "yyyyMMdd") + Math.abs(IdUtil.fastSimpleUUID().hashCode()));
        userMapper.addUser(user);
    }

    //通过id查询用户
    @Override
    public User getById(Integer id) {
        return userMapper.getById(id);


    }

    @Override
    public void update(User user) {
        user.setUpdateTime(new Date());
        userMapper.updateById(user);
    }

    @Override
    public void deleteById(Integer id) {
        userMapper.deleteById(id);
    }

    //充值
    @Override
    public void addAccount(User user) {
        Integer score = user.getScore();
        if (score==null){
            return;
        }
        //不信任前端查出来的数据，我们从后端查出来
        Integer id = user.getId();
        User dbUser = userMapper.getById(id);
        dbUser.setAccount(dbUser.getAccount()+score);
        userMapper.updateById(dbUser);

    }
}
